package com.sunshuo.springsecuritydemo.dao;

import com.sunshuo.springsecuritydemo.pojo.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @ClassName UserRoleDao
 * @Description
 * @Author sunshuo
 * @Date 2021/11/7 20:58
 */
@Repository
public class UserRoleDao {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<UserRole> getRoleRelationsByUserId(String userId) {
        String sql = "select * from t_user_role where user_id = ?";
        return jdbcTemplate.query(sql, new RowMapper<UserRole>() {
            @Override
            public UserRole mapRow(ResultSet rs, int rowNum) throws SQLException {
                UserRole userRole = new UserRole();
                userRole.setUserId(rs.getString("user_id"));
                userRole.setRoleId(rs.getString("role_id"));
                return userRole;
            }
        }, userId);
    }

    public void deleteByUserId(String userId) {
        String sql = "delete from t_user_role where user_id = ?";
        jdbcTemplate.update(sql, userId);
    }

    public void add(UserRole userRole) {
        String sql = "insert into t_user_role values(?, ?)";
        jdbcTemplate.update(sql, userRole.getUserId(), userRole.getRoleId());
    }
}
